package cn.sytton.taffe.framework.util;

import cn.sytton.taffe.framework.security.entity.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * 登录用户工具类
 *
 * @author skyrock
 */
@Slf4j
public class SecurityUtil {

    public static String getUserId() {
        return getLoginUser().getUserId();
    }

    public static String getUserCode() {
        return getLoginUser().getUserCode();
    }

    public static String getUserName() {
        return getLoginUser().getUserName();
    }

    public static String getLoginName() {
        return getLoginUser().getLoginName();
    }

    public static String getEmail() {
        return getLoginUser().getEmail();
    }

    public static String getCellphone() {
        return getLoginUser().getCellphone();
    }

    public static String getUserStatus() {
        return getLoginUser().getUserStatus();
    }

    public static Date getExpireDate() {
        return getLoginUser().getExpireDate();
    }

    public static Set<String> getUserRoles() {
        return getLoginUser().getUserRoles();
    }

    public static String getIp() {
        return getLoginUser().getIp();
    }

    public static String getLoginLocation() {
        return getLoginUser().getLoginLocation();
    }

    public static String getBrowser() {
        return getLoginUser().getBrowser();
    }

    public static String getOs() {
        return getLoginUser().getOs();
    }

    public static Date getLoginTime() {
        return getLoginUser().getLoginTime();
    }

    public static Map<String, String> getExtInfo() {
        return getLoginUser().getExtInfo();
    }

    public static Date getTokenRefreshTime() {
        return new Date(getLoginUser().getTokenRefreshTimeStamp());
    }

    public static Date getTokenExpireTime() {
        return new Date(getLoginUser().getTokenExpireTimeStamp());
    }

    /**
     * 获取登录用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            if (getAuthentication() == null) {
                log.warn("获取用户异常:" + e.getMessage());
            } else if (!"anonymousUser".equals(getAuthentication().getPrincipal())) {
                log.error("获取用户异常:", e);
            }
            return new LoginUser();
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static boolean isLogin() {
        return (getAuthentication() != null && getAuthentication().getPrincipal() != null);
    }
}
